package com.lcke.common.login;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.ContentType;
import com.lcke.common.except.ExceptionController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器模式，使用拦截器的好处是这是 servlet 容器提供的方法，直接注入 spring即可配置，
 * 放行路径和拦截路径配置需要手动
 */
@Slf4j
@Component
public class LoginFilter extends OncePerRequestFilter {

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) throws ServletException {
        return super.shouldNotFilter(request);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 配置跨域
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType(ContentType.JSON.getValue());
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE");
        //X-CAF-Authorization-Token,sessionToken,X-TOKEN
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Origin,X-Request-With,Content-Type,Accept,token,tssotoken");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "*");
        response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, "*");
        //log.info("过滤器-" + System.currentTimeMillis());
        try {
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            log.info("未知异常", e);
            request.setAttribute("javax.servlet.error.status_code", 500);
            request.setAttribute("error", e.getMessage());
            request.getRequestDispatcher(ExceptionController.ERROR_PATH).forward(request, response);
        }
    }
}
